<?php

namespace App\Admin\Repositories;

use App\Models\UserMessage as Model;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Repositories\EloquentRepository;
use Illuminate\Support\Facades\DB;

class UserMessage extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    public function get(Grid\Model $model)
    {
       $data = $this->eloquentClass::select(['content','created_at'])->groupBy('content','created_at')->get();
       $total = $this->eloquentClass::select(['content','created_at'])->groupBy('content','created_at')->count('id');

        return $model->makePaginator(
            $total ?? 0, // 传入总记录数
            $data ?? [] // 传入数据二维数组
        );
    }

    public function store(Form $form)
    {
        $updated = $form->updates();

        $content = $updated['content'];

        DB::table('users')
            ->orderBy('id')
            ->chunk(50,function ($users) use ($content){
                $messages = [];
                foreach ($users as $user){
                    $messages[] = [
                        'type' =>1,
                        'user_id' => $user->id,
                        'is_read' =>1,
                        'content' => $content,
                        'created_at' => date('Y-m-d H:i:s')
                    ];
                }
                if ($messages){
                    DB::table('user_messages')->insert($messages);
                }
            });

        return true;
    }
}
